package com.ctrl.riveradministrator.mvp.view.activity.problem_report;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.ctrl.riveradministrator.R;
import com.ctrl.riveradministrator.base.BaseActivity;
import com.ctrl.riveradministrator.common.Constants;
import com.ctrl.riveradministrator.mvp.model.Problem;
import com.ctrl.riveradministrator.mvp.presenter.ProblemReportPresenter;
import com.ctrl.riveradministrator.mvp.view.activity.illegal_report.GridViewAdapter;
import com.ctrl.riveradministrator.mvp.view.weight.ImageViewActivity;
import com.ctrl.riveradministrator.util.PictureSelectorConfig;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;

public class ReportActivity extends BaseActivity<ProblemReportPresenter> implements
        AdapterView.OnItemClickListener, ProblemReportView {

    private Toolbar toolbar;
    private TextView titleTv;
    private ImageView leftMenu;
    private Button submit;
    private EditText type, content;
    private Spinner person;
    private ProgressBar bar;
    private static SharedPreferences sp;

    private GridView gridView;

    private GridViewAdapter gridViewAdapter;
    private ArrayList<String> mPicList = new ArrayList<>(); //上传的图片的数据源
    private String personId = "-1";


    @Override
    protected void initParams(Bundle parms) {

    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_report;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void initView(View view) {
        sp = getSharedPreferences(Constants.TRACE_SP, MODE_PRIVATE);
        toolbar = $(R.id.toolbar);
        titleTv = $(R.id.title_tv);
        leftMenu = $(R.id.left_iv);
        gridView = $(R.id.gridView);
        submit = $(R.id.submit_btn);
        type = $(R.id.type);
        content = $(R.id.content);
        person = $(R.id.person);
        bar = $(R.id.probar);

        /*
         * 设置toolbar
         * */
        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.setTitle("");
        titleTv.setText(R.string.problem_report);
        leftMenu.setBackground(getDrawable(R.drawable.ic_chevron_left_24dp));

        gridViewAdapter = new GridViewAdapter(this, mPicList);
        gridView.setAdapter(gridViewAdapter);
    }

    @Override
    protected void doBusiness(Context mContext) {
        //bar.setVisibility(View.VISIBLE);
        //mPresenter.getPerson();
    }

    @Override
    protected void widgetClick(View view) {
        switch (view.getId()) {
            case R.id.left_iv:
                finish();
                break;
            case R.id.submit_btn:
                //提交前进行空判断
                //首先上传文字，然后再上传图片，期间不可以中断
                if(TextUtils.isEmpty(content.getText().toString())){
                    Toast.makeText(this, "问题上报详情不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(mPicList.size() == 0){
                    Toast.makeText(this, "图片不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                bar.setVisibility(View.VISIBLE);
                mPresenter.report(mPicList, content.getText().toString(),sp.getString(Constants.TRACE_TASK_ID, "-1"),personId);
                break;
        }
    }

    @Override
    protected void setListener() {
        leftMenu.setOnClickListener(this);
        gridView.setOnItemClickListener(this);
        submit.setOnClickListener(this);
    }

    @Override
    public void handleMessage(Message message, int what) {

    }

    @Override
    protected ProblemReportPresenter createPresenter() {
        return new ProblemReportPresenter(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, ImageViewActivity.class);
        if (mPicList.size() == 1) {
            Log.d("ReportActivity", "::" + mPicList.get(position));
            intent.putExtra("img_url", mPicList.get(position));
            intent.putExtra("type", "local");
            startActivity(intent);
        } else {
            PictureSelectorConfig.initMultiConfig(this, 1 - mPicList.size());
        }
      /*  Intent intent = new Intent(this, ImageViewActivity.class);
        if (position == parent.getChildCount() - 1) {
            //如果“增加按钮形状的”图片的位置是最后一张，且添加了的图片的数量不超过5张，才能点击
            if (mPicList.size() == 5) {
                //最多添加5张图片
                intent.putStringArrayListExtra("img_list", mPicList);
                intent.putExtra("position", position);
                startActivityForResult(intent, 10);
            } else {
                //添加图片
                intent.putStringArrayListExtra("img_list", mPicList);
                intent.putExtra("position", position);
                PictureSelectorConfig.initMultiConfig(this, 5 - mPicList.size());
            }
        } else {
            intent.putExtra("img_url", mPicList.get(position));
            intent.putExtra("type", "local");
            startActivity(intent);
        }*/

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("aaa", "::" + requestCode);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    for (LocalMedia localMedia : PictureSelector.obtainMultipleResult(data)) {
                        //被压缩后的图片路径
                        if (localMedia.isCompressed()) {
                            String compressPath = localMedia.getCompressPath(); //压缩后的图片路径
                            Log.d("compressPath", "::" + compressPath);
                            mPicList.add(compressPath); //把图片添加到将要上传的图片数组中
                            gridViewAdapter.notifyDataSetChanged();
                        }
                    }
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    break;
                case PictureConfig.CAMERA:
                    for (LocalMedia localMedia : PictureSelector.obtainMultipleResult(data)) {
                        //被压缩后的图片路径
                        if (localMedia.isCompressed()) {
                            String compressPath = localMedia.getCompressPath(); //压缩后的图片路径
                            Log.d("compressPath", "::" + compressPath);
                            mPicList.add(compressPath); //把图片添加到将要上传的图片数组中
                            gridViewAdapter.notifyDataSetChanged();
                        }
                    }
                    break;
            }
        }
       /* if (requestCode == 10 && resultCode == 11) {
            //查看大图页面删除了图片
            ArrayList<String> toDeletePicList = data.getStringArrayListExtra("img_list"); //要删除的图片的集合
            mPicList.clear();
            mPicList.addAll(toDeletePicList);
            gridViewAdapter.notifyDataSetChanged();
        }*/
    }

    @Override
    public void showMessage() {
        bar.setVisibility(View.GONE);
        submit.setText("上报成功");
        Toast.makeText(this, "上报成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showMessage(List<Problem> problem) {
        List<String> name = new ArrayList<>();
        for (int i = 0; i < problem.size(); i++) {
            name.add(problem.get(i).getUserName());
        }
        ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name);
        person.setAdapter(adapter);
        person.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                personId = problem.get(position).getUserId();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        bar.setVisibility(View.GONE);
    }

    @Override
    public void showError(String msg) {
        bar.setVisibility(View.GONE);
        Toast.makeText(this, "上报失败:"+msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void uploading(String percent) {

    }
}
